/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-08-20 10:18:51
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-08-21 09:03:17
 * @FilePath: /vue3-uniapp/src/pages/tabbar/AreaOrderList/useList.ts
 */
import {
    useMy,
    OrderSearchRequestParam,
    useAreaEsListSubscribe
} from '@/service/useMy';
import type { MyAreaEsListItem } from '@/typings/api/my';
import { useUserStore } from '@/store/index';
import type { mescrollViewInstance } from '@/components/ui/MescrollView/typings';
import { useAfterAuth } from '@/service/hook/useAfterAuth';

export const useList = () => {
    const { areaEsList, areaEsTotal, getAreaEsList } = useMy();
    const { currentAreaLevel, currentAreaCode, currentDeptId, roleType } =
        storeToRefs(useUserStore());

    const param = ref(new OrderSearchRequestParam());
    const list = ref<MyAreaEsListItem[]>([]);

    const getList = () => {
        if (roleType.value === 'area') {
            param.value.areaLevel = currentAreaLevel.value;
            param.value.areaCode = currentAreaCode.value;
            if (currentAreaLevel.value && currentAreaCode.value) {
                param.value.searchAreaList = [
                    {
                        areaLevel: currentAreaLevel.value,
                        areaCode: currentAreaCode.value
                    }
                ];
            }
        } else if (roleType.value === 'depart') {
            param.value.departmentId = currentDeptId.value;
            if (currentDeptId.value) {
                param.value.searchDepartmentIdList = [currentDeptId.value];
            }
        }

        return getAreaEsList(param.value).then((res) => {
            if (param.value.current === 1) {
                list.value = [];
            }
            list.value = [...list.value, ...areaEsList.value];
            return res;
        });
    };

    const confirm = () => {
        param.value.current = 1;
        getList();
    };

    const reset = () => {
        param.value = new OrderSearchRequestParam();
        getList();
    };
    useAreaEsListSubscribe((state) => {
        param.value = {
            ...param.value,
            ...state
        };
        getList();
    });

    return {
        param,
        datas: areaEsList,
        list,
        listTotal: areaEsTotal,
        getList,
        confirm,
        reset
    };
};
